import React, {Component} from 'react';
import ReactEcharts from 'echarts-for-react';
import {connect} from 'react-redux';
import actionMsg from '../../store/actions/socketMsgs';
import {getCity} from '../../api';
import {Tag} from 'antd';
import './MainHome.scss';
import 'animate.css';

class MainHome extends Component {
  state = {
    data: []
  };
  getOption = () => {
    const {dataSource} = this.props;
    return dataSource;
  };
  initCity = async () => {
    try {
      const tempData = await getCity();
      let {data} = tempData;
      data = data.map(item => {
        return {
          ...item,
          color: `rgb(${Math.floor(Math.random() * 150)},${Math.floor(Math.random() * 150)},${Math.floor(Math.random() * 150)})`
        };
      });
      this.setState({
        data
      });
    } catch (e) {
      console.log(e);
    }

  };

  componentDidMount() {
    const nav = JSON.parse(localStorage.getItem('mynav'));
    const path = nav[0].path
    let flag = false;
    nav.forEach(item => {
      console.log(item);
      if (item.title === '首页') {
        flag = true;
      }
    });
    if (!flag) {
      this.props.history.push(path);
    }
    this.initCity();
    setInterval(() => {
      this.initCity();
    }, 50000);
  }

  render() {
    const {data} = this.state;
    return (
      <div className='mainHome animated slideInDown'>
        <div className='echartTitle'>
          <h1>七日访问量({this.props.total})</h1>
        </div>
        <ReactEcharts
          option={this.getOption() || {}}
          className='react_for_echarts'
          style={{height: '350px', width: '100%'}}/>
        <ul className={'citys'}>
          {
            data.length && data.map((item, index) => (
              <Tag color={item.color} key={index + item.city}>{item.city}({item.today})</Tag>
            ))
          }
        </ul>
      </div>
    );
  }
}

const mapStateToProps = state => state.leftNav;
export default connect(mapStateToProps, actionMsg)(MainHome);
